package net.simo.servicebook.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import net.simo.servicebook.model.security.Role;
import net.simo.servicebook.model.security.User;

@Stateless
public class UserManager {
	@Inject
	private EntityManager em;

	public User findUser(String email, String password) {
		// @formatter:off
		String hql = "" + "FROM User u " + "INNER JOIN FETCH u.person "
				+ "INNER JOIN FETCH u.role "
				+ "WHERE u.email = :email AND u.password = :password";
		// @formatter:on
		TypedQuery<User> query = em.createQuery(hql, User.class);
		query.setParameter("email", email);
		query.setParameter("password", password);
		List<User> result = query.getResultList();
		if (result.isEmpty()) {
			return null;
		}
		if (result.size() > 1) {
			throw new RuntimeException("");
		}
		return result.get(0);
	}

	public void saveUser(User user) {
		em.persist(user);
	}

	public List<Role> selectRole() {
		String hql = "FROM Role";

		TypedQuery<Role> query = em.createQuery(hql, Role.class);
		List<Role> result = query.getResultList();
		return result;
	}
}
